﻿using System;
using EmbeddedSharp.Core;
using Zove.Runtime.Core;

namespace Zove.Scripting.Core.Functions {

    /// <summary>
    /// Check if an instance belongs to a particular type.
    /// </summary>
    [Function("isInstanceOf", "Check if an instance belongs to a particular type.",
        "circle c;\n\rresult=isInstanceOf(c, \"circle\");", "result==true")]
    public class IsInstanceOfNode : ZoveScriptingContextFuncNode {

        /// <summary>
        /// Default constructor
        /// </summary>
        public IsInstanceOfNode() :
            base("isInstanceOf") {
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public override object Evaluate() {
            int count = Parameters.Count;

            if (Parameters.Count < 2) {
                throw new ArgumentException(
                    "usage: isInstanceOf(instance, className);");
            }

            string instanceName = Parameters[count - 1].Value;
            string className = Convert.ToString(Parameters[count - 2].Evaluate());

            ZoveObject instance = ZoveShellContext.GetInstance(instanceName);
            if (instance == null) {
                return false;
            }

            return instance.Model.Name == className;
        }
    }
}
